﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using SharePoint.Sunbox.Sandbox.Resources;

namespace SharePoint.Sunbox.Sandbox.DataViewWebPart
{
    public class DataSourcesEditorPart : EditorPart
    {
        private readonly HiddenField _hiddenSourceValue;

        public DataSourcesEditorPart()
        {
            _hiddenSourceValue = new HiddenField { ID = "datasourcedata" };
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            string webUrl = SPContext.Current.Site.RootWeb.Url;
            Controls.Add(_hiddenSourceValue);

            Controls.Add(
                new LiteralControl(string.Format(
                    "<link rel='stylesheet' type='text/css' href='{0}/Style%20Library/SunBox/SunboxDataView/css/editorpart.css' />",
                    webUrl)));
            Controls.Add(
                new LiteralControl(string.Format(
                    "<link rel='stylesheet' type='text/css' href='{0}/Style%20Library/SunBox/Scripts/fancybox/jquery.fancybox.css' />",
                    webUrl)));
            Controls.Add(
                new LiteralControl(string.Format(
                    "<link rel='stylesheet' type='text/css' href='{0}/Style%20Library/SunBox/SunboxDataView/css/codemirror.css' />",
                    webUrl)));

            /*  SCRIPTS  */
            ReferencePrevalidatedScript("JSON",
                                        string.Format("{0}/Style%20Library/Sunbox/SunboxDataView/Scripts/json2.js",
                                                      webUrl));
            //jquery:
            ReferencePrevalidatedScript("jQuery",
                            string.Format("{0}/Style%20Library/Sunbox/Scripts/jquery.js",
                                          webUrl));

            ReferencePrevalidatedScript("$.fancybox",
                                        string.Format(
                                            "{0}/Style%20Library/SunBox/Scripts/fancybox/jquery.fancybox.pack.js",
                                            webUrl));
            ReferencePrevalidatedScript("CodeMirror",
                                        string.Format(
                                            "{0}/Style%20Library/SunBox/SunboxDataView/Scripts/codemirror.js", webUrl));
            //reference language pack:
            ReferenceLanguagePack(Properties.Language, webUrl);

            Controls.Add(
                new LiteralControl(
                    string.Format(
                        "<script type='text/javascript' src='{0}/Style%20Library/SunBox/SunboxDataView/Scripts/sunbox.dataview.dseditorpart.js'></script>",
                        webUrl)));

            string containerId = Guid.NewGuid().ToString();
            Controls.Add(new LiteralControl(string.Format("<div id='{0}'></div>", containerId)));
            Controls.Add(
                new LiteralControl(string.Format(
                    "<script>var __xsldatasourceseditorpart = $('#{0}').datasourceeditorpart({{controlid:'{1}', lang:'{2}'}});</script>",
                    containerId,
                    _hiddenSourceValue.ClientID,
                    Properties.Language)));
        }

        public override bool ApplyChanges()
        {
            try
            {
                var webpart = WebPartToEdit as DataViewWebPart;
                if (webpart == null) return false;

                webpart.DataSourcesData = _hiddenSourceValue.Value;
            }
            catch (Exception)
            {
                return true;
            }
            return true;
        }

        public override void SyncChanges()
        {
            var webpart = WebPartToEdit as DataViewWebPart;
            if (webpart == null) return;
            _hiddenSourceValue.Value = webpart.DataSourcesData;
        }

        private void ReferencePrevalidatedScript(string objectToValidate, string scriptPath)
        {
            Controls.Add(new LiteralControl(string.Format(
                @"<script>if (typeof ({0}) == ""undefined"") {{
                                                                document.write(""<script"" + "" src='{1}'><"" + ""/script>"");
                                                                }}
                                                            </script>",
                objectToValidate, scriptPath)));
        }

        private void ReferenceLanguagePack(string language, string webUrl)
        {
            Controls.Add(new LiteralControl(string.Format(
                @"<script>if (typeof (SunboxDataView.lang) == ""undefined"" || typeof(SunboxDataView.lang.{0}) == ""undefined"") {{
                                                                document.write(""<script"" + "" src='{1}/Style%20Library/SunBox/SunboxDataView/Scripts/lang/{0}.js'><"" + ""/script>"");
                                                                }}
                                                            </script>",
                language, webUrl)));
        }
    }
}